package com.sentrix.auto.printercenter.application;

import com.sentrix.auto.printercenter.domain.entity.PrinterAgentEntity;
import com.sentrix.auto.printercenter.infrastructure.persistence.IAgentRepository;
import com.sentrix.auto.printercenter.presentation.center.dto.AgentResDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class AgentService {

    private final IAgentRepository agentRepository;

    @Transactional
    public void handleConnect(String macAddress, String sessionId) {
        PrinterAgentEntity agentEntity = agentRepository.findByCode(macAddress).orElse(new PrinterAgentEntity());
        if(StringUtils.isBlank(agentEntity.getCode())){
            agentEntity.setCode(macAddress);
            agentEntity.setName(macAddress);
        }
        agentEntity.connect(sessionId);
        agentRepository.online(agentEntity);
    }

    @Transactional
    public void handleDisconnect(String mac) {
        Optional<PrinterAgentEntity> agentEntity = agentRepository.findByCode(mac);
        agentEntity.ifPresent(entity -> {
            entity.disconnect();
            agentRepository.offline(entity);
        });
    }

    public <R> List<R> queryAll(Function<PrinterAgentEntity, R> convert) {
        List<PrinterAgentEntity> agents = agentRepository.list();
        return agents.stream().map(convert).collect(Collectors.toList());
    }
}
